using System.Collections.Generic;
using UnityEngine;

// 建筑网格系统，用于管理建筑在网格上的放置
public class BuildingGrid : MonoBehaviour
{
    [SerializeField]
    private int width;  // 网格的宽度（X轴方向格子数量）

    [SerializeField]
    private int height; // 网格的高度（Z轴方向格子数量）

    private BuildingGridCell[,] grid; // 二维数组存储所有网格单元格

    // 初始化网格
    private void Start()
    {
        // 根据设定的宽高创建网格
        grid = new BuildingGridCell[width, height];

        // 初始化每个网格单元格
        for (int x = 0; x < grid.GetLength(0); x++)
        {
            for (int y = 0; y < grid.GetLength(1); y++)
                grid[x, y] = new BuildingGridCell();
        }
    }

    // 在网格上放置建筑
    public void SetBuilding(Building building, List<Vector3> allBuildingPositions)
    {
        // 遍历建筑所有单元位置
        foreach (var p in allBuildingPositions)
        {
            // 将世界坐标转换为网格坐标
            (int x, int y) = WorldToGridPosition(p);
            // 在对应网格单元格设置建筑
            grid[x, y].SetBuilding(building);
        }
    }

    // 世界坐标转网格坐标
    private (int x, int y) WorldToGridPosition(Vector3 worldPosition)
    {
        // 计算相对于原点的网格坐标（X轴）
        int x = Mathf.FloorToInt((worldPosition - transform.position).x / BuildingSystem.CellSize);
        // 计算相对于原点的网格坐标（Z轴，对应网格Y）
        int y = Mathf.FloorToInt((worldPosition - transform.position).z / BuildingSystem.CellSize);
        return (x, y);
    }

    // 检查是否可以建造
    public bool CanBuild(List<Vector3> allBuildingPositions)
    {
        foreach (var p in allBuildingPositions)
        {
            (int x, int y) = WorldToGridPosition(p);

            // 检查是否超出网格范围
            if (x < 0 || x >= width || y < 0 || y >= height)
                return false;

            // 检查单元格是否已被占用
            if (!grid[x, y].IsEmpty())
                return false;
        }
        return true;
    }

    // 在Scene视图绘制网格Gizmo
    void OnDrawGizmos()
    {
        Gizmos.color = Color.yellow;

        // 参数无效时不绘制
        if (BuildingSystem.CellSize <= 0 || width <= 0 || height <= 0)
            return;

        Vector3 origin = transform.position;

        // 绘制横向网格线（Z轴方向）
        for (int y = 0; y <= height; y++)
        {
            Vector3 start = origin + new Vector3(0, 0.01f, y * BuildingSystem.CellSize);
            Vector3 end = origin + new Vector3(width * BuildingSystem.CellSize, 0.01f, y * BuildingSystem.CellSize);
            Gizmos.DrawLine(start, end);
        }

        // 绘制纵向网格线（X轴方向）
        for (int x = 0; x <= width; x++)
        {
            Vector3 start = origin + new Vector3(x * BuildingSystem.CellSize, 0.01f, 0);
            Vector3 end = origin + new Vector3(x * BuildingSystem.CellSize, 0.01f, height * BuildingSystem.CellSize);
            Gizmos.DrawLine(start, end);
        }
    }
}